// src/hooks/useWebSocket.ts
import { ref, onMounted, onUnmounted, Ref } from 'vue';

interface WebSocketHook {
	isConnected: Ref<boolean>;
	connect: (url: string) => void;
	send: (data: any) => void;
	close: () => void;
	messages: Ref<string[]>;
}

export function useWebSocket(): WebSocketHook {
	const socket = ref<WebSocket | null>(null);
	const isConnected = ref(false);
	const messages = ref<string[]>([]);

	const connect = (url: string) => {
		if (!socket.value) {
			socket.value = new WebSocket(url);
		}

		socket.value!.onopen = () => {
			isConnected.value = true;
			console.log('WebSocket connected');
		};

		socket.value!.onmessage = event => {
			messages.value.push(event.data);
		};

		socket.value!.onclose = () => {
			isConnected.value = false;
			console.log('WebSocket disconnected');
		};
	};

	const send = (data: any) => {
		if (socket.value && socket.value.readyState === WebSocket.OPEN) {
			socket.value.send(JSON.stringify(data));
		}
	};

	const close = () => {
		if (socket.value) {
			socket.value.close();
		}
	};

	// 设置生命周期钩子
	onMounted(() => {
		// 连接 WebSocket
		// connect('ws://your-websocket-url');
	});

	onUnmounted(() => {
		// 断开 WebSocket 连接
		close();
	});

	return {
		isConnected,
		connect,
		send,
		close,
		messages
	};
}
